import time
from selenium import webdriver
from selenium.webdriver.common.by import By

class Test():
    def setup_method(self):
        self.driver = webdriver.Edge()
        self.vars = {}

    def teardown_method(self):
        self.driver.quit()

    def test_(self):
        self.driver.get("https://top.baidu.com/board?tab=realtime")
        self.driver.set_window_size(882, 692)
        self.driver.find_element(By.CSS_SELECTOR, ".tab-item_17MbK:nth-child(2) > span").click()
        time.sleep(1)
        self.vars["count"] = "1"
        titleList = []
        while self.driver.execute_script("return (arguments[0]<10)", self.vars["count"]):
            self.vars["title"] = self.driver.find_element(By.CSS_SELECTOR,
                                                          ".category-wrap_iQLoo:nth-child(%s) .c-single-text-ellipsis" %
                                                          self.vars["count"]).text
            titleList.append(self.vars["title"])
            print(self.vars["title"])
            self.vars["count"] = self.driver.execute_script("return parseInt(arguments[0])+1", self.vars["count"])
            with open("title1.txt", "w", encoding="utf-8") as file:
                for titleItem in titleList:
                    print(titleItem)
                    file.write(titleItem + '\n')

T = Test()
T.setup_method()
T.test_()